const fs = require("fs");
const path = require("path");

const first = ["Id"];
const last = ["UpdateBy", "UpdateAt", "CreateBy", "CreateAt"];

const colPattern = /^\s*(\w+)\s*/;

/**
 *
 * @param {string} columnsBlock
 * @returns
 */
function reorderColumnsBlock(columnsBlock) {
   const lines = columnsBlock
      .split("\n")
      .filter(e => /\S/.test(e))
      .map(e => e.replace(/^( ){2,}/g, ""));

   /** @type {Map<string, string[]>} */
   const lineTeams = new Map();

   let teamKey = "";
   lines.forEach(e => {
      // 删除结尾的 “，”
      e = e.replace(/,$/, "");

      if (/( = )/.test(e)) {
         const match = e.match(/^[^\s]+/);
         teamKey = match[0];
         lineTeams.set(teamKey, [e]);
      } else {
         const team = lineTeams.get(teamKey);
         team.push(e);
      }
   });

   /** @type {string[]} */
   const keys = [];

   lineTeams.forEach((value, key) => keys.push(key));

   const middle = keys.filter(c => !first.includes(c) && !last.includes(c));
   const order = [...first, ...middle, ...last];
   const actualOrder = order.filter(e => keys.includes(e));

   let columns = "";

   const space = " ".repeat(4 * 5);

   let orderEnd = actualOrder.length - 1;

   for (let i = 0; i <= orderEnd; i++) {
      const val = lineTeams.get(actualOrder[i]);

      const len = val.length - 1;
      for (let j = 0; j <= len; j++) {
         let n = j == 0 ? 0 : 1;
         const spaceNext = " ".repeat(4 * n);

         columns += `${space}${spaceNext}${val[j]}`;

         if (j == len && i != orderEnd) columns += ",";

         columns += "\n";
      }
   }

   return columns;
}

function processFile(filePath) {
   try {
      let content = fs.readFileSync(filePath, "utf8");
      const pattern = /columns:\s*table\s*=>\s*new\s*{([^}]+)},/gs;

      content = content.replace("\r\n", "\n");

      content = content.replace(pattern, (match, block) => {
         const newBlock = reorderColumnsBlock(block);
         const space = " ".repeat(4 * 4);

         let line = `columns: table => new\n`;
         line += space + "{\n";
         line += newBlock;
         line += space + "},";
         return line;
      });

      fs.writeFileSync(filePath, content, "utf8");
      console.log(`已处理: ${filePath}`);
   } catch (err) {
      console.error(`处理文件时出错 ${filePath}:`, err);
   }
}

function main() {
   const migrationsDir = path.join(__dirname, "..", "StudentVideo.Data", "Migrations");
   const pattern = /^\d+_updateDatabase\d+\.cs$/;

   try {
      const files = fs.readdirSync(migrationsDir);
      for (const file of files) {
         if (pattern.test(file)) {
            processFile(path.join(migrationsDir, file));
         }
      }
   } catch (err) {
      console.error("读取迁移目录时出错:", err);
   }
}

if (require.main === module) {
   main();
}
